package com.example.demo.util;

import com.example.demo.course.Course;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;

@Component
public class EmailUtil {

    @Value("${spring.mail.host}")
    private String host; // SMTP服务器

    @Value("${spring.mail.port}")
    private int port; // 端口号

    @Value("${spring.mail.username}")
    private String username; // 发件邮箱

    @Value("${spring.mail.password}")
    private String password; // 授权码

    public void sendReminder(String toEmail, Course course) throws MessagingException {
        // 1. 配置邮件服务器
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);

        // 2. 创建会话
        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        // 3. 构建邮件内容
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject("【课程提醒】" + course.getName());

        String content = String.format(
                "课程名称：%s\n时间：%s\n地点：%s\n教师：%s",
                course.getName(),
                course.getTime(),
                course.getLocation(),
                course.getTeacher()
        );
        message.setText(content);

        // 4. 发送邮件
        Transport.send(message);
    }
}